#include "imgui/math/Editor.h"

using namespace ImGui::Math;

bool Editor::Edit(Ogl::Math::Transform& inst)
{
	ImGui::PushID(&inst);
	bool res = false;
    res |= ImGui::DragFloat3("Pos", &inst.position.x);
    res |= ImGui::DragFloat3("Rot", &inst.rotation.x);
    res |= ImGui::DragFloat3("Scl", &inst.scale.x);
	ImGui::PopID();

    return res;
}

bool ImGui::Math::Editor::Edit(Ogl::Math::Frustum &inst)
{
	ImGui::PushID(&inst);

	bool res = false;
	res |= ImGui::DragFloat("fov", &inst.fovy, 1.0f, 0.0f, 180.0f);
    res |= ImGui::DragFloat("aspect", &inst.aspect, 0.1f,0.0f);    ;
    res |= ImGui::DragFloat("near_z", &inst.nNear, 1.0f, 0.1f);
    res |= ImGui::DragFloat("far_z", &inst.nFar, 1.0f, 0.1f);
    
	ImGui::PopID();
    return res;
}

bool ImGui::Math::Editor::FreeMove(Ogl::Math::Transform& transform, const WorkDesc& desc)
{

	bool res = false;

	ImGuiIO& io = ImGui::GetIO();

	float deltaTime = io.DeltaTime;

	ImGui::PushID(&transform);
	float frontInput = 0.0f;
	if (ImGui::IsKeyDown(ImGuiKey_W))
	{
		frontInput = 1.0f;
	}
	if (ImGui::IsKeyDown(ImGuiKey_S))
	{
		frontInput = -1.0f;
	}
	float dist = frontInput * desc.walkSpeed * deltaTime;;
	transform.Translate(dist);

	float turnInput = 0.0f;
	if (ImGui::IsKeyDown(ImGuiKey_A))
	{
		turnInput = 1.0f;
	}

	if (ImGui::IsKeyDown(ImGuiKey_D))
	{
		turnInput = -1.0f;
	}
	float delteRight = turnInput * desc.trunSpeed * deltaTime;

	transform.MoveRight(delteRight);

	if (ImGui::IsMouseDragging(ImGuiMouseButton_Left))
	{
		ImVec2 rotInput = io.MouseDelta;
		float rotX = desc.rotSpeedX * deltaTime * rotInput.x;
		float rotY = desc.rotSpeedY * deltaTime * rotInput.y;

		transform.RotateY(-rotX);
		transform.RotateX(rotY);
	}


	ImGui::PopID();


	return false;
}

bool ImGui::Math::Editor::DragMove(Ogl::Math::Transform& transform, const MoveDesc& desc)
{
	ImGuiIO& io = ImGui::GetIO();
	ImVec2 delta = io.MouseDelta;
	float deltaY = io.MouseDelta.y;
	float deltaX = io.MouseDelta.x;

	if (ImGui::IsMouseDragging(ImGuiMouseButton_Middle))
	{
		transform.GetPosXY();
		glm::vec3 deltaPos = transform.GetUp() * deltaY + transform.GetRight() * deltaX;
		float des = 0.0f;
		des = std::abs(transform.position.y);
		transform.position += deltaPos * des * desc.middleMoveAxis;
	}
	else if (io.MouseWheel != 0.0f)
	{
		transform.Translate(io.MouseWheel * desc.mWheelSpeed);
	}
	else if (ImGui::IsMouseDragging(ImGuiMouseButton_Right))
	{
		glm::vec3 xzPos = transform.GetPosXZ();
		float dist = glm::length(transform.position - xzPos);

		glm::vec3 pos = transform.GetPosXZ();
		glm::vec3 rot = transform.rotation;

		transform.RotateY(-deltaX * desc.rotYspeed);
		transform.RotateX(deltaY * desc.rotXspeed);

		transform.rotation.x = glm::clamp(transform.rotation.x, -89.0f, 89.0f);;

		glm::vec3 newPos = xzPos - dist * transform.GetForward();

		transform.position = newPos;
		transform.LookAt(xzPos, glm::vec3(0.0f, 1.0f, 0.0f));

	}

	return false;
}
